package com.example.kill.config;

import com.alibaba.druid.util.StringUtils;
import com.example.kill.pojo.KillUser;
import com.example.kill.service.KillUserService;
import com.example.kill.service.impl.KillUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserArgumentResolvers implements HandlerMethodArgumentResolver {

    @Autowired
    private KillUserService userService;


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> clazz =  methodParameter.getParameterType();
        return clazz== KillUser.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest  request   =  nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response  = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String parameToken = request.getParameter(KillUserServiceImpl.COOKI_NAME_TOKEN);
        String cookieToken = getCookieValue(request,KillUserServiceImpl.COOKI_NAME_TOKEN);
        if (StringUtils.isEmpty(parameToken) && StringUtils.isEmpty(cookieToken))
        {
            return null ;
        }
        String token = StringUtils.isEmpty(parameToken)?cookieToken:parameToken;

        return userService.getKillUserByToken(response,token); 
    }

    private String getCookieValue(HttpServletRequest request, String cookiName) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie: cookies ) {
            if (cookie.getName().equals(cookiName)){
                return cookie.getValue();
            }
        }
        return  null ;
    }
}
